<template>
  <div class="app-container customer-div">
    <el-menu :default-active="trackingParams.type" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我负责的</el-menu-item>
      <el-menu-item index="all" v-if="isAllPurchaseTracking">全部</el-menu-item>
    </el-menu>

    <!-- <div style="margin-top: 20px">
      <el-button
        size="small"
        @click="showTracking('add',null)"
        type="primary">
        新增跟进记录
      </el-button>
    </div> -->

    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="trackingParams" size="mini" label-width="100px">
        <el-form-item label="供应商名称：">
          <el-select
            clearable
            v-model="trackingParams.supplierId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod3"
            :loading="loading">
            <el-option
              v-for="item in supplierList2"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人：">
          <el-select
            v-model="trackingParams.contactId"
            filterable
            remote
            clearable
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod2"
            :loading="loading2">
            <el-option v-for="item in contactList2"  :key="item.contactId" :label="item.contactName" :value="item.contactId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容：">
          <el-input v-model="trackingParams.trackingContent" clearable></el-input>
        </el-form-item>
        <el-form-item label="跟进方式：">
          <el-select  v-model="trackingParams.followUpId" placeholder="请选择" clearable multiple>
            <el-option v-for="item in trackingMethodList" :key="item.tmId" :value="item.tmId" :label="item.trackingMethod"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进人：" v-if="trackingParams.type=='all'">
          <el-select v-model="trackingParams.trackingUserId" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期：">
          <el-date-picker
            style="width: 300px;"
            :default-time="['00:00:00', '23:59:59']"
            v-model="trackingParams.createTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            range-separator="——"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="跟进等级：">
          <el-select v-model="trackingParams.supplierLevel" class="input-width" placeholder="请选择" clearable>
            <el-option v-for="(item,index) in supplierLevelList" :key="index" :value="item" :label="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <!-- <el-button
            v-if="purchaseTrackingExport"
            @click="downloadExcel">
            导出
          </el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="trackingLoading"
        :data="trackingList"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          label="供应商名称"
          width="260">
            <template slot-scope="scope">
              <el-link @click="toDetail(scope.row)" type="primary">
                {{scope.row.customerName}}
              </el-link>
            </template>
        </el-table-column>
        <el-table-column
          prop="contactName"
          label="联系人姓名"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="supplierLevel"
          label="跟进等级"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="followUpValue"
          label="跟进方式"
          align="center"
          width="100">
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="trackingMethodValue"-->
<!--          label="沟通方式"-->
<!--          align="center"-->
<!--          width="100">-->
<!--        </el-table-column>-->
        <el-table-column
          prop="trackingPurposeValue"
          label="跟进目的"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="trackingContent"
          label="跟进内容"
          align="left"
          width="300">
        </el-table-column>
        <el-table-column
          prop="trackingContent"
          label="上游情况"
          align="left"
          width="300">
          <template slot-scope="{row}">
               <div>当前库存：{{row.currentStock}}</div>
               <div>每天产能：{{row.dayCapacity}}</div>
               <div>当天卖货量：{{row.todayOrderNum}}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="trackingPics"
          label="附件"
          align="center"
          width="250">
          <template slot-scope="{row}">
            <div v-if="row.trackingPics.length>0">
            <div v-for="(item,index) in row.trackingPics" :key="index" :class="{imgStyle:checkFileType(item)=='image'}">
              <!-- 音频 -->
              <div v-if="checkFileType(item)=='audio'">
                <audio controls style="width: 220px; height: 30px">
                  <source :src="item" type="audio/mpeg" />
                  <source :src="item" type="audio/ogg" />
                  <source :src="item" type="audio/mp3" />
                  您的浏览器不支持该音频格式。
                </audio>
              </div>
              <!-- 图片 -->
              <div v-else-if="checkFileType(item)=='image'" style="width: 40px;margin-right:10px">
                <el-image
                  style="width: 40px; height: 40px;"
                  :src="item"
                  :preview-src-list="Array(item)">
                </el-image>
              </div>
              <div v-else>
                <div>{{ item }}</div>
              </div>
            </div>
          </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="trackingTime"
          label="跟进日期"
          width="150"
          align="center">
        </el-table-column>
        <el-table-column
          prop="trackingUser"
          label="跟进人"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="isInvalid"
          label="目的是否完成"
          width="100"
          align="center">
          <template slot-scope="{row}">
            <div>{{ row.isInvalid==1?'是':'否' }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="nextTrackingTime"
          label="下次跟进时间"
          width="150"
          align="center">
        </el-table-column>
        <el-table-column
          width="150"
          fixed="right"
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              v-if="trackingParams.type == 'my'"
              type="text"
              size="mini"
              @click="showSupplierGj('edit',scope.row)">编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="showSupplierGj('see',scope.row)">查看
            </el-button>
            <el-button
              v-if="trackingParams.type == 'my'"
              type="text"
              size="mini"
              @click="delTracking(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChangeTracking"
        @current-change="handleCurrentChangeTracking"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="trackingParams.pageNum"
        :page-size="trackingParams.pageSize"
        :page-sizes="[10,15,20]"
        :total="trackingCount">
      </el-pagination>
    </div>

    <!-- 新增跟进 -->
    <addSupplierGj ref="addSupplierGj" @update="getTrackingListData"></addSupplierGj>

  </div>
</template>

<script>
import {
  supplierTrackingList,
  supplierDelTracking,
  getOrderUsersList,
} from '@/api/partner';
import {
  getTrackingMethodListAPI2,
} from "@/api/fms.js";
import {
  supplierListApi,
  commonSupplierContactList,
  supplierConstantAPI
} from '@/api/company';
import { formatDate } from '@/utils/date';
import store from '@/store';
import { mapGetters } from 'vuex';
import addSupplierGj from './components/addSupplierGj.vue';
const defaultTrackingParams = {
  type: 'my',
  supplierId: '',
  contactId: '',
  trackingContent: '',
  followUpId: [],
  trackingUserId: '',
  createTime: [],
  supplierLevel:'',
  pageNum: 1,
  pageSize: 10,
};
export default {
  name: "purchaseTrackingDetail",
  data() {
    return {
      trackingMethodList:[],
      roles: store.getters.roles ? store.getters.roles : [],
      trackingParams:JSON.parse(JSON.stringify(defaultTrackingParams)),
      trackingList: [],
      trackingCount: 0,
      trackingLoading: false,
      contactList2: [],//联系人列表
      loading: false,
      userOptionList: [],
      supplierList2: [],
      loading3: false,
      loading2: false,
      supplierLevelList:[],
    }
  },
  components: {
    addSupplierGj,
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    isAllPurchaseTracking() {
      if (this.roles.indexOf("allPurchaseTracking") != -1) {
        return true
      } else {
        return false
      }
    },
    purchaseTrackingExport() {
      if (this.roles.indexOf("purchaseTrackingExport") != -1) {
        return true
      } else {
        return false
      }
    },
  },
  created() {
    // this.getcustomerTrackingList();
    // this.getUploadToken();
    // this.getSupplierGradeList();
    this.getTrackingListData();
    this.getUserOptionList();
    this.getTrackingMethodList();
    this.getSupplierLevelList();
  },
  filters: {
    formatTime(time) {
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd')
    },
  },
  methods: {
     // 编辑跟进
    showSupplierGj(type, item) {
      if (type == 'add') {
        this.$refs.addSupplierGj.showPop(type,item)
      } else if (type == 'edit') {
        this.$refs.addSupplierGj.showPop(type,item)
      } else if (type == 'see') {
        this.$refs.addSupplierGj.showPop(type,item)
      }
    },
    // 判断文件类型
    checkFileType(fileName) {
      if (fileName.match(/\.(jpg|jpeg|png|gif|webp)/)) {
        return "image";
      } else if (fileName.match(/\.(doc|docx)/)) {
        return "word";
      } else if (fileName.match(/\.(wav|mp3|aac|ogg|wma)/)) {
        return "audio";
      } else {
        return "unknown";
      }
    },
    //获取供应商等级列表
    getSupplierLevelList() {
      supplierConstantAPI().then((res) => {
        this.supplierLevelList = res.supplierLevel;
      })
    },
    //跟进方式
    getTrackingMethodList(){
      getTrackingMethodListAPI2({pageNum:1,pageSize: 1000,isEnable:1}).then((res)=>{
        this.trackingMethodList = res.list
      })
    },

    //获取供应商列表
    remoteMethod3(query) {
      if (query && query != '') {
        this.loading3 = true;
        //获取供应产列表
        supplierListApi({ tab: this.trackingParams.type, supplierName: query, pageNum: 1, pageSize: 1000 }).then(response => {
          this.supplierList2 = response.list;
          this.loading3 = false;
        }).catch(() => {
          this.loading3 = false;
        });

      }
    },

    //查询获取联系人列表
    remoteMethod2(query) {
      if (query && query != '') {
        this.loading2 = true;
        commonSupplierContactList({ contactName: query }).then(response => {
          this.contactList2 = response;
          this.loading2 = false;
        }).catch(() => {
          this.loading2 = false;
        });
      }
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },


    //去详情页
    toDetail(item) {
      let routeData = this.$router.resolve({ name: 'supplierInfo', query: { id: item.supplierId } });
      window.open(routeData.href);
    },
    /**
     * 切换选择状态
     */
    handleSelect(key, keyPath) {
      this.trackingParams = JSON.parse(JSON.stringify(defaultTrackingParams));
      this.trackingParams.type = key;
      this.handleSearchList();
    },
    //获取员工下拉选项
    getUserOptionList() {
      getOrderUsersList({departmentType:"purchase"}).then((res) => {
        this.userOptionList = res;
      })
    },

    handleSearchList() {
      this.trackingParams.pageNum = 1;
      this.getTrackingListData();
    },
    //获取跟进记录
    getTrackingListData() {
      this.trackingLoading = true;
      let data = JSON.parse(JSON.stringify(this.trackingParams));
      // if (data.createTime && data.createTime != '') {
      //   data.createTime[0] = data.createTime[0] / 1000;
      //   data.createTime[1] = data.createTime[1] / 1000;
      // }
      supplierTrackingList(data).then((res) => {
        this.trackingList = res.list;
        this.trackingCount = res.count;
        this.trackingLoading = false;
      }).catch(() => {
        this.trackingLoading = false;
      })
    },

    handleSizeChangeTracking(val) {
      this.trackingParams.pageNum = 1;
      this.trackingParams.pageSize = val;
      this.getTrackingListData();
    },
    handleCurrentChangeTracking(val) {
      this.trackingParams.pageNum = val;
      this.getTrackingListData();
    },
    //删除跟进
    delTracking(item) {
      this.$confirm('确定删除跟进记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        supplierDelTracking({ trackingId: item.trackingId }).then(() => {
          this.getTrackingListData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //切换公司
    // changeCustomerId() {
    //   this.trackingForm.contactId = null;
    //   this.getContactListData()
    // },

     //获取供应商列表
    // remoteMethod(query) {
    //   if (query && query != '') {
    //     this.loading = true;
    //     supplierList({ supplierName: query }).then(response => {
    //       this.supplierList = response;
    //       this.loading = false;
    //     }).catch(() => {
    //       this.loading = false;
    //     });
    //   }
    // },

    //下载excle
    // downloadExcel() {
    //   let data = JSON.parse(JSON.stringify(this.trackingParams));
    //   data.isExport = 1;
    //   supplierTrackingList(data).then((res) => {
    //     require.ensure([], () => {
    //       const { export_json_to_excel } = require('sheet/Export2Excel');
    //       const tHeader = res.title;
    //       const filterVal = res.columns;
    //       const list = res.list;
    //       const data = this.formatJson(filterVal, list);
    //       export_json_to_excel(tHeader, data, res.fileName);
    //     })
    //   })
    // },

  },
};
</script>

<style scoped lang="scss">
.imgStyle{
  float: left;
}
</style>
